package com.lixueju.security.box.web.demo.exception;

import com.alibaba.fastjson.JSONObject;
import com.lixueju.security.box.core.dto.ResultData;
import com.lixueju.security.box.core.exception.SecurityBoxException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lixueju
 * @since 2019/10/15 9:39
 **/
@ControllerAdvice//控制器增强
public class AuthExceptionCatch {
    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
    //捕获CustomException此类异常
    @ExceptionHandler(SecurityBoxException.class)
    @ResponseBody
    public ResultData securityBoxException(SecurityBoxException securityBoxException) {
        securityBoxException.printStackTrace();
        //记录日志
        LOGGER.error("catch exception:{}", JSONObject.toJSONString(securityBoxException.getResultData()));
        return securityBoxException.getResultData();
    }


    //捕获AuthenticationException此类异常
    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public ResultData authenticationException(AuthenticationException authenticationException) {
        authenticationException.printStackTrace();
        //记录日志
        return new ResultData(new Integer("999"), authenticationException.getLocalizedMessage(),null);
    }

    //捕获CustomException此类异常
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public ResultData accessDeniedException(AccessDeniedException accessDeniedException) {
        accessDeniedException.printStackTrace();
        //记录日志
        return new ResultData(new Integer("999"), "xxxx",accessDeniedException.getLocalizedMessage());
    }

    //捕获Exception此类异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultData exception(Exception exception) {
        exception.printStackTrace();
        //记录日志
        LOGGER.error("catch excseption:\b\n{}", exception);

        //未定义的异常统一返回99999异常
        return new ResultData(new Integer("999"), "xxxx",null);
    }
}
